package com.tanhua.server.service;


import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.db.UserInfo;
import com.tanhua.model.domain.mongodb.FocusUser;
import com.tanhua.model.domain.mongodb.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author maorf
 * @version 1.0
 */
@Service
public class SmallViSdeosService {

    @Autowired
    private OssTemplate ossTemplate;
    //从调度服务器获取，一个目标存储服务器，上传
    @Autowired
    private FastFileStorageClient client;
    @Autowired
    private FdfsWebServer webServer;// 获取存储服务器的请求URL
    @DubboReference
    private VideoApi videoApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @CacheEvict(value = "videoList",allEntries = true)
    public ResponseEntity upload(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1、封面图上传到阿里云OSS，获取地址
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //2、视频上传到fdfs上，获取请求地址
        //获取文件的后缀名
        String filename = videoFile.getOriginalFilename();  //ssss.avi
        String sufix = filename.substring(filename.lastIndexOf(".")+1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(),
                videoFile.getSize(), sufix, null);//文件输入流，文件长度，文件后缀，元数据
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //3、创建Video对象，并设置属性
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API完成保存
        videoApi.save(video);
        //5、构造返回值
        return ResponseEntity.ok(null);
    }

    //小视频列表
    @Cacheable(value="videoList",key="#page + '_' +  #pagesize")
    public PageResult getSmallVideos(Integer page, Integer pagesize) {
        PageResult pageResult = videoApi.getSmallVideos(page,pagesize, UserHolder.getUserId());
        if (pageResult.getItems()==null){
            return pageResult;
        }
        List<Video> items = (List<Video>) pageResult.getItems();
        List<VideoVo> list = new ArrayList<>();
        for (Video item : items) {
            UserInfo userInfo = userInfoApi.findUserInfoById(item.getUserId());
            VideoVo videoVo = new VideoVo();
            videoVo.setId(String.valueOf(item.getId()));
            videoVo.setUserId(Math.toIntExact(userInfo.getId()));
            videoVo.setAvatar(userInfo.getAvatar());
            videoVo.setVideoUrl(item.getVideoUrl());
            videoVo.setNickname(userInfo.getNickname());
            videoVo.setCover(item.getPicUrl());
            list.add(videoVo);
        }
        pageResult.setItems(list);
        return pageResult;
    }

    //关注视频作者
    public void userFocus(Long followUserId) {
        //1、创建FollowUser对象，并设置属性
        FocusUser followUser = new FocusUser();
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(followUserId);
        //2、调用API保存
        videoApi.saveFocusUser(followUser);
        //3、将关注记录存入redis中
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().put(key,hashKey,"1");
    }

    //取消关注视频作者
    public void userUnFocus(Long followUserId) {
        //1、调用API删除关注数据
        videoApi.deleteFollowUser(UserHolder.getUserId(),followUserId);
        //2、删除redis中关注记录
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(followUserId);
        redisTemplate.opsForHash().delete(key,hashKey);
    }
}
